import NProgress from 'nprogress' // progress bar
import 'nprogress/nprogress.css' // progress bar style
import router from './router'
import store from '@/store'
import getPageTitle from '@/utils/get-page-title'
import { asyncRoutes } from '@/router/index'
// 白名单数组
const whiteList = ['/login', '/404']

router.beforeEach(async(to, from, next) => {
  NProgress.start()
  const token = store.state.user.token
  if (token) {
    if (to.path === '/login') {
      // 有token，还去登录 ---> 直接去主页
      console.log('有token，还去登录 ---> 直接去主页')
      next('/')
      NProgress.done()
    } else {
      // 1. 获取个人信息
      if (!store.getters.userId) {
        // console.log(asyncRoutes)
        const res = await store.dispatch('user/getUserInfo')
        const menus = res.data.roles.menus
        const filterRoutes = asyncRoutes.filter(item => {
          const name = item.name
          return menus.includes(name)
        })

        // 把404加到最后一条
        filterRoutes.push( // 404 page must be placed at the end !!!
          { path: '*', redirect: '/404', hidden: true })
        console.log('路由守卫', filterRoutes, asyncRoutes, res.data.roles.menus)
        // 动态添加可以访问的路由设置
        router.addRoutes(filterRoutes)
        // 根据用户实际能访问几个页面来决定从整体8个路由设置
        // 中，过滤中出来几个，然后保存到vuex中
        store.commit('menu/updateMenuList', filterRoutes)
      }
      next()
    }
  } else {
    // 没有token，只能访问白名单
    if (whiteList.includes(to.path)) {
      next()
    } else {
      console.log('没有token，只能访问白名单')
      next('/login')
      NProgress.done()
    }
    // whiteList.includes(to.path) ? next() : next('/login')
  }
  // console.log(token, '路由跳转', from.path, '----->', to.path)
})
// 路由守卫可以写多个
router.beforeEach((to, from, next) => {
  document.title = getPageTitle(to.meta.title)
  next()
})

router.afterEach(() => {
  NProgress.done()
})
